<?php

namespace App\Kuafu\User\Controller\H5;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Log\Model\UserLoginLogModel;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\User\Enum\CodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\AuthException;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserService;
use App\Kuafu\User\Validate\UserValidate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LoginController extends BaseController
{
    /**
     * 用户登录
     *
     * @param Request $request
     * @return JsonResponse
     * @throws AuthException
     * @throws UserException
     * @throws \App\Kuafu\Sms\Exceptions\SmsException
     */
    public function login(Request $request)
    {
        $valid = UserValidate::loginValid($request);
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_SERVER_ERROR, $valid);
        }

        $smsType = $request->smsType ?: SmsService::CODE_TYPE_SUPPLY_LOGIN;

        $mobile = $request->username;
        SmsService::verifyCode($mobile, $request->code, $smsType);

        $res = AuthService::mobileLogin($mobile, UserCodeEnum::H5_TYPE, $request->isLasting,
            (string)$request->ip());

        $expiredTimestamp = time() + (config('jwt.ttl') * 120);
        //判断是否为首次登录
        $isFirstLogin = UserService::isFirstLogin($request) ? UserLoginLogModel::USER_LOGIN_FIRST_YSE : UserLoginLogModel::USER_LOGIN_FIRST_NO;
        return $this->success([
            'token'            => $res,
            'expiredTimestamp' => $expiredTimestamp,
            'isFirstLogin'     => $isFirstLogin
        ]);
    }

}
